<script setup>
import {onMounted, onUnmounted, ref, watch} from "vue"
import {ElMessage} from "element-plus";
import {getCategoryService} from "@/api/category.js"
import {getQualityService} from "@/api/quality.js";
import {Plus} from "@element-plus/icons-vue";
import {useTokenStore} from "@/stores/token.js";
import {pushGoodsService} from "@/api/goods.js";
import {useRouter} from "vue-router";
import {getUserInfoService} from "@/api/user.js";
import {getQwenVLService} from "@/api/AITalk.js";
import {baseUrl} from "@/utils/request.js";

const route = useRouter();
const title = ref('')
const categoryList = ref([])
const qualityList = ref([])

const tokenStore = useTokenStore();

onMounted(()=>{
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;
})


const getCategoryList = async () => {
  let result = await getCategoryService()
  categoryList.value = result.data
}
const getQualityList = async () => {
  let result = await getQualityService()
  qualityList.value = result.data
}
//获取分类和成色列表
getCategoryList();
getQualityList();

const loadingTexts = [
  "AI正在生成商品信息，请稍后",
  "AI正在生成商品信息，请稍后.",
  "AI正在生成商品信息，请稍后. .",
  "AI正在生成商品信息，请稍后. . .",
  "AI正在生成商品信息，请稍后. . . .",
  "AI正在生成商品信息，请稍后. . . . ."
]
const isLoading = ref(false)
const isShowWarning = ref(false)
const index = ref(0)
const currentLoadingText = ref(loadingTexts[index.value])

const intervalId = setInterval(() => {
  index.value = (index.value + 1) % loadingTexts.length
  currentLoadingText.value = loadingTexts[index.value]
}, 500)

const goods = ref({
  goodsName: "",
  price: "",
  description: "",
  categoryId: "",
  pic: "",
  qualityId: ""
})


//校验规则
const rules = ref({
  goodsName: [
    {required: true, message: "请输入商品名称", trigger: "blur"}
  ],
  price: [
    {required: true, message: "请输入商品价格", trigger: "blur"},
    {type: Number, message: "请输入正确价格", trigger: "blur"},
  ],
  description: [
    // {required: true, message: "请输入商品描述", trigger: "blur"},
    //   {min: 5, max: 200, message: "长度在 5 到 200 个字符", trigger: "blur"}
  ],
  categoryId: [
    {required: true, message: "请选择商品分类", trigger: "blur"}
  ],
  pic: [
    {required: true, message: "请上传商品图片", trigger: "blur"}
  ],
  qualityId: [
    {required: true, message: "请选择商品质量", trigger: "blur"}
  ]
})
//上传图片请求的后端地址
const uploadUrl = ref(baseUrl+"/file/upload")
const uploadSuccess = (result) => {
  goods.value.pic = result.data;
  isLoading.value = true
  ElMessage.success("上传成功")
}
const beforeUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M")
    return false
  } else if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("图片格式不正确")
    return false
  }
  return true
}

watch(isLoading, async (newValue, oldValue) => {
  if (newValue) {
    try {
      let result = await getQwenVLService(goods.value.pic)
      goods.value.description = result.data.description;
      goods.value.goodsName = result.data.title;
      goods.value.categoryId = result.data.categoryId;
      goods.value.qualityId = result.data.qualityId;
      goods.value.price = result.data.price;
      isShowWarning.value = true;
    } catch (e) {
      ElMessage.error("AI生成失败")
      isLoading.value = false;
    }
  }
})

//发布商品
const pushGoods = async () => {
  if (goods.value.goodsName === ""){
    ElMessage.error("请输入商品名称")
    return
  }
  if (goods.value.price < 0) {
    ElMessage.error("价格不能小于零")
    return
  }
  if (goods.value.pic === "") {
    ElMessage.error("请上传商品图片")
    return
  }
  if (goods.value.description === "") {
    ElMessage.error("请输入商品描述")
    return
  }
  if (goods.value.description.length <= 0 || goods.value.description.length > 200) {
    ElMessage.error("商品描述长度需为0~200")
    return
  }
  if (goods.value.goodsName.length<0 || goods.value.goodsName.length > 40){
    ElMessage.error("商品名称长度需为0~40")
    return
  }
  let result = await pushGoodsService(goods.value);
  if (result.code === 0) {
    ElMessage.success("发布成功")
    route.push("/")
  }
}

const goBack = () => {
  window.history.go(-1)
}

onUnmounted(()=>{
  clearInterval(intervalId);
})
</script>

<template>
  <el-container class="container">
    <el-form ref="form" :model="goods" :rules="rules" label-width="auto" style="max-width: 440px" class="form">
      <el-form-item label="商品图片:" prop="pic">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="multipartFile"
            :headers="{ 'Authorization': tokenStore.token }"
            :auto-upload="true"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
        >
          <img v-if="goods.pic" :src="goods.pic" class="avatar" alt="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
        <div style="margin-top: 0" slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
      </el-form-item>
      <el-form-item label="商品名称:" prop="goodsName">
        <el-input v-model="goods.goodsName"/>
      </el-form-item>
      <el-form-item label="商品价格:" prop="price">
        <el-input v-model="goods.price"/>
      </el-form-item>
      <el-form-item label="商品成色:" prop="qualityId">
        <el-select v-model="goods.qualityId" placeholder="请选择商品成色">
          <el-option v-for="item in qualityList" :key="item.id" :label="item.qualityName" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品分类:" prop="categoryId">
        <el-select v-model="goods.categoryId" placeholder="请选择商品分类">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品描述:" prop="description">
        <el-input v-model="goods.description" type="textarea" resize="none"/>
      </el-form-item>
      <p
          v-if="isLoading"
          style="margin-top: -16px;margin-bottom: 8px;font-size: 13px;margin-left: 90px;color: #ee0fee;"
      >{{ !isShowWarning ? currentLoadingText : "AI生成内容可能有误，请注意甄别。" }}</p>
      <el-text class="mx-1" type="warning">注意：发布商品须收取定价1%的手续费，最高收取2元，须熟知。</el-text>
      <el-button @click="goBack" class="goBackButton">返回</el-button>
      <el-button type="primary" @click="pushGoods" class="pushButton">发布商品</el-button>
      <div class="clearfix"></div>
    </el-form>
  </el-container>
</template>

<style scoped>
.container {
  background-color: #fcfcfc;
  width: 500px;
  height: 620px;
  margin: 60px auto 0;
  display: flex; /* 使用 Flex 布局 */
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .mx-1 {
    margin-right: 10px;
  }

  .form {
    margin-top: 20px;
    margin-left: 30px;
  }

  .pushButton {
    margin-top: 20px;
    float: right;
  }

  .goBackButton {
    margin-top: 20px;
  }

  .clearfix::after {
    content: "";
    display: table;
    clear: both;
  }
}

.avatar-uploader .avatar {
  width: 168px;
  height: 168px;
  display: block;
  object-fit: cover;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>